package http

import (
	"context"
	"fileserver/config"
	"fileserver/logger"
	"log"
	"net/http"
	"os"
	"os/signal"
	"path/filepath"
	"strconv"
	"time"
)

func addHandler(mux *http.ServeMux) {
	hostConfig := config.Config.Host
	for _, folderConfig := range config.Config.Folders {
		prefix := filepath.Join(hostConfig.Prefix, folderConfig.Prefix) + "/"
		fs := http.FileServer(http.Dir(folderConfig.Path))
		mux.Handle(prefix, http.StripPrefix(prefix, fs))
		logger.Info("前缀: %s, 目录: %s", prefix, folderConfig.Path)
	}
}

func Init() {
	hostConfig := config.Config.Host
	mux := http.NewServeMux()
	addHandler(mux)
	addr := ":" + strconv.Itoa(hostConfig.Port)
	server := &http.Server{
		Addr:         addr,
		Handler:      mux,
		ReadTimeout:  time.Minute,
		WriteTimeout: time.Minute,
	}
	go func() {
		logger.Info("Http服务器 [%s] 启动成功, 端口: %d ...", hostConfig.Name, hostConfig.Port)
		if err := server.ListenAndServe(); err != nil {
			logger.Error("Http服务器 [%s] 启动失败, %v", hostConfig.Name, err)
		}
	}()

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	<-c
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
	defer cancel()
	server.Shutdown(ctx)
	log.Println("Http服务器 [%s] 关闭", hostConfig.Name)
}
